package xyz.jcat.spring.security.example.filter;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import xyz.jcat.common.util.ObjectUtils;
import xyz.jcat.common.web.Resp;
import xyz.jcat.common.web.RespCodeMsg;
import xyz.jcat.web.WebUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class ValidateCodeFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //拦截登录请求
        if(Objects.equals(request.getRequestURI(), "/login")) {
            String validateCode = request.getParameter("validateCode");
            //TODO
            if(ObjectUtils.notEquals(validateCode, "123456")) {
                WebUtils.writeJson(response, Resp.fail(RespCodeMsg.CAPTCHA_ERROR));
                return;
            }
        }

        filterChain.doFilter(request, response);
    }
}
